iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
Software Development

Vibe Unity - AI時代的遊戲開發工作流系列 第 16

Day 16 - Groq API 免費開源的文本生成模型

  • 分享至 

  • xImage
  •  

今天要來介紹一款很酷的 AI 平台 - Groq (不是Grok )

https://groq.com/

image.png

Groq 提供超快的API回傳速度,支援多種開源的LLM模型

重點是它提供免費API的方案,也就是前期測試的時候,可以完全不花錢

只需要注意免費版的Rate Limit即可: https://console.groq.com/docs/rate-limits

image.png

那我們今天就在 Unity 中實現 Groq API 的功能

由於 Groq 只是一個 LLM 對話的平台, 所以我們只需要考慮對話的功能就好

GroqAICore:

using System;
using System.Collections;
using System.Text;
using Core;
using Newtonsoft.Json;
using PolarAI.Scripts.AICore.Groq.Model;
using UnityEngine;
using UnityEngine.Networking;

namespace PolarAI.Scripts.AICore.Groq
{
    public class GroqAICore
    {
        private string ApiKey = "YOUR_GROQ_API_KEY";
        private string AIModel = "openai/gpt-oss-120b";
        private float Temperature = 0.2f;
        private const string ChatCompletionsUrl = "https://api.groq.com/openai/v1/chat/completions";

        public void Initialize(string apiKey)
        {
            ApiKey = apiKey;
        }

        public void SetModel(string model)
        {
            AIModel = model;
        }

        public void SetTemperature(float temperature)
        {
            Temperature = temperature;
        }

        public void SendChat(string role, string prompt, Action<string, bool> onCompleted)
        {
            if (string.IsNullOrEmpty(ApiKey))
            {
                Debug.LogWarning("【Error】Please Initialize Groq API Key First.");
                return;
            }

            var req = new ChatRequest
            {
                Model = AIModel,
                Temperature = Temperature,
                Messages = new[]
                {
                    new ChatMessage(role, prompt)
                }
            };

            CoroutineManager.Instance.StartCoroutine(SendChatCoroutine(req, onCompleted));
        }

        public void SendChatList(ChatMessage[] chatMessages, Action<string, bool> onCompleted)
        {
            if (string.IsNullOrEmpty(ApiKey))
            {
                Debug.LogWarning("【Error】Please Initialize Groq API Key First.");
                return;
            }

            var req = new ChatRequest
            {
                Model = AIModel,
                Temperature = Temperature,
                Messages = chatMessages
            };

            CoroutineManager.Instance.StartCoroutine(SendChatCoroutine(req, onCompleted));
        }

        private IEnumerator SendChatCoroutine(ChatRequest request, Action<string, bool> onCompleted)
        {
            var json = JsonConvert.SerializeObject(request);
            var body = Encoding.UTF8.GetBytes(json);

            using var www = new UnityWebRequest(ChatCompletionsUrl, "POST");
            www.uploadHandler = new UploadHandlerRaw(body);
            www.downloadHandler = new DownloadHandlerBuffer();
            www.SetRequestHeader("Authorization", "Bearer " + ApiKey);
            www.SetRequestHeader("Content-Type", "application/json");
            yield return www.SendWebRequest();

            var isError = www.result != UnityWebRequest.Result.Success;
            if (isError)
            {
                onCompleted?.Invoke($"【HTTP {www.responseCode}】{www.error}\n{www.downloadHandler.text}", false);
                yield break;
            }

            var responseText = www.downloadHandler.text;
            try
            {
                var resp = JsonConvert.DeserializeObject<ChatResponse>(responseText);
                var content = resp?.Choices is { Length: > 0 } ? resp.Choices[0].Message?.Content : null;

                if (string.IsNullOrEmpty(content))
                {
                    onCompleted?.Invoke("【Error】Reply Content Is Empty .\nRaw:\n" + responseText, false);
                }
                else
                {
                    onCompleted?.Invoke(content.Trim(), true);
                }
            }
            catch (Exception ex)
            {
                onCompleted?.Invoke("【JSON Deserialize Error】" + ex.Message + "\nRaw:\n" + responseText, false);
            }
        }
    }
}

上面的代碼是我們的API呼叫核心

接下來我們可以寫一個簡單的UI界面來調用它

快速使用(單次對話):

GroqAICore ai = new GroqAICore();
ai.Initialize("YOUR_KEY");
ai.SetModel("openai/gpt-oss-120b");
ai.SendChat("user", "幫我生成 3 句歡迎詞", (content, ok) =>
{
    Debug.Log(ok ? content : "Error: " + content);
});

多輪對話(保留上下文):

var messages = new[]
{
    new ChatMessage("system", "你是專業的遊戲文案助手"),
    new ChatMessage("user", "幫我寫角色介紹,風格史詩奇幻")
};
GroqAICore ai = new GroqAICore();
ai.Initialize("YOUR_KEY");
ai.SetModel("openai/gpt-oss-120b");
ai.SendChatList(messages, (content, ok) => { /* 更新 UI */ });

image.png

Unity UI Example:

using UnityEngine;
using UnityEngine.UI;

namespace PolarAI.Scripts.AICore.Groq.Example
{
    public class GroqExample : MonoBehaviour
    {
        [Header("Groq Settings")] 
        
        [SerializeField]
        [Tooltip("Get Groq API: https://console.groq.com/keys")] 
        private string apiKey = "YOUR_GROQ_API_KEY";

        [SerializeField]
        [Tooltip("Check Groq Model: https://console.groq.com/home")] 
        private string model = "openai/gpt-oss-120b";

        [Range(0f, 2f)] 
        [SerializeField] private float temperature = 0.2f;

        [Header("UI (Unity UI)")] 
        [SerializeField]
        private Button sendButton; // 拖入要測試的 Button

        [SerializeField] private InputField inputField; // 也可留空,會用預設提示
        [SerializeField] private Text outputText; // 顯示結果

        private GroqAICore GroqAICore = new();

        private void Start()
        {
            GroqAICore.Initialize(apiKey);
            GroqAICore.SetModel(model);
            GroqAICore.SetTemperature(temperature);
            if (sendButton != null) sendButton.onClick.AddListener(OnClickSend);
            
        }

        private void OnDisable()
        {
            if (sendButton != null) sendButton.onClick.RemoveListener(OnClickSend);
        }

        private void OnClickSend()
        {
            if (string.IsNullOrEmpty(apiKey))
            {
                Debug.Log("【Error】Please Set Groq API Key First.");
                return;
            }

            GroqAICore.SendChat("user", inputField.text, (content, isSuccess) =>
            {
                outputText.text = content;
            });
        }

      
    }
}

上一篇
Day 15 - Fal AI API網站功能介紹
下一篇
Day 17 - OLlama 本地化的AI模型 API
系列文
Vibe Unity - AI時代的遊戲開發工作流30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言